import React, { createContext, useReducer, useState, useEffect } from "react";
import { Alert } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import query from "../../api/query";
import { fileWeb } from "../../api/query";
import { useSelector } from "react-redux";
import axios from "axios";

const ResearchContext = createContext();

const dataReducer = (state, action) => {
  switch (action.type) {
    case "fetch_init":
      return action.payload;
    case "add_research":
      return [...state, action.payload];
    case "edit_research": //传入试卷对象
      return state.map((item) => {
        return item._id === action.payload._id ? action.payload : item;
      });
    case "delete_research": //传入试卷_id
      return state.filter((item) => item._id !== action.payload);
  }
};

export const ResearchProvider = ({ children }) => {
  const [researchLists, dispatch] = useReducer(dataReducer, []);
  const [isResearchLoading, setIsResearchLoading] = useState(false);
  const [isResearchError, setIsResearchError] = useState(false);

  const user = useSelector((state) => state.authR.user);

  useEffect(() => {
    const fetchData = async () => {
      setIsResearchLoading(true);
      setIsResearchError(false);

      try {
        const token = await AsyncStorage.getItem("token");
        const result = await query.get("/report/" + user._id, {
          headers: { Authorization: token },
        });
        dispatch({ type: "fetch_init", payload: result.data.data });
      } catch (err) {
        setIsResearchError(true);

        console.log("初始化调研报告出错", err);
      }
      setIsResearchLoading(false);
    };
    fetchData();
  }, []);

  const addResearch = async (localFile, callback) => {
    try {
      setIsResearchLoading(true);
      let formData = new FormData();
      formData.append("file", {
        name: localFile.uri.split("/").pop(),
        uri: localFile.uri,
        type: localFile.mimeType,
      });

      //上传文档至文件服务器
      let res = await fetch(fileWeb + "/upload", {
        method: "post",
        headers: {
          "Content-Type": "multipart/form-data",
        },
        body: formData,
      });
      let response = await res.json();
      // console.log("====================================");
      // console.log(response.message);
      // console.log("====================================");

      //上传记录
      let mytime = new Date();
      let myitem = {
        userId: user._id,
        time: mytime,
        fileName: localFile.name,
        type: "pending",
        fileObject: response.message,
      };

      const token = await AsyncStorage.getItem("token");
      const result = await query.post("/report", myitem, {
        headers: { Authorization: token },
      });

      dispatch({ type: "add_research", payload: result.data.data });
      Alert.alert("", "调研报告提交成功", [
        {
          text: "确定",
          onPress: () => callback(), //setIsSelect(false)
        },
      ]);
    } catch (err) {
      console.log("调研报告提交失败", err);
      Alert.alert("", "调研报告提交失败");
    }
    setIsResearchLoading(false);
  };

  const deleteResearch = async (research) => {
    try {
      setIsResearchLoading(true);
      await axios.delete(fileWeb + "/upload/" + research.fileObject._id);

      const token = await AsyncStorage.getItem("token");
      await query.delete("/report/" + research._id, {
        headers: { Authorization: token },
      });
      dispatch({ type: "delete_research", payload: research._id });
      Alert.alert("", "调研报告删除成功", [
        {
          text: "确定",
        },
      ]);
    } catch (err) {
      console.log("删除调研报告出错", err);
      Alert.alert("", "删除调研报告失败");
    }
    setIsResearchLoading(false);
  };

  return (
    <ResearchContext.Provider
      value={{
        researchLists: researchLists,
        addResearch,
        deleteResearch,
        isResearchLoading,
      }}
    >
      {children}
    </ResearchContext.Provider>
  );
};

export default ResearchContext;
